package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.QuestionAndAnswerInfoDao;
import com.juyu.miliao.api.dao.mysql.QuestionAndAnswerPayInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.QuestionAndAnswerPayInfoRedisDao;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import com.juyu.miliao.common.constant.RecordTypeEnum;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author xuanqicheng
 * @create 2018-19-2:09 PM
 */
@Service
@Slf4j
public class QuestionAndAnswerPayService {

    private static final Integer PAY_GOLD_NUMBER = 5;

    @Autowired
    private QuestionAndAnswerPayInfoDao questionAndAnswerPayInfoDao;

    @Autowired
    private QuestionAndAnswerPayInfoRedisDao questionAndAnswerPayInfoRedisDao;

    @Autowired
    private QuestionAndAnswerInfoDao questionAndAnswerInfoDao;

    @Resource
    private AppKeyService appkeyService;

    @Autowired
    private UserWalletDao userWalletDao;

    @Autowired
    private BillDetailDao billDetailDao;
    /**
     * 购买下单
     * @param condition
     * @param userId 购买这id
     */
    @Transactional(rollbackFor = Exception.class)
    public void createInfo(QuestionAndAnswerPayCondition condition, long  userId) {

        Appkey appkey =appkeyService.getAppKeyByKey("giftRatio");

        double diamond = DoubleFormatUtil.doubleFormate(PAY_GOLD_NUMBER * Double.parseDouble(appkey.getValue()));

        //根据id 获取问题
        QuestionAndAnswerInfo obj = questionAndAnswerInfoDao.selectOne(condition.getQuestionId());

        //判断购买人身份，
        if(userId == obj.getQuestionUserId() || userId == obj.getAnswerUserId() ){
            throw  new ConsumeRuntimeException("购买这身份不合法");
        }

        //判断用户是否购买过
        boolean bl=questionAndAnswerPayInfoRedisDao.checkUserIsBy(condition.getQuestionId(),userId);

        if(bl){
            throw  new ConsumeRuntimeException("此用户已经购买过，请勿重复购买");
        }

        //判断购买用户金币是否充足
        UserWallet userWallet = userWalletDao.getUserWalletById(userId);

        log.info("用户：{},账号余额：{}",userId,userWallet.getDeposit());

        if(userWallet.getDeposit()<PAY_GOLD_NUMBER){

            throw new ConsumeRuntimeException("金币不足，请充值金币");
        }

        //下单 1：非主播页面偷听，2：主播页面偷听
        if(condition.getType()==2){
            //收益为平台
            UserWallet entity = new UserWallet();

            entity.setUserId(userId);

            entity.setDeposit(PAY_GOLD_NUMBER);

            // 减提问者金币
            userWalletDao.minusDeposit(entity);


            log.info("用户：{}偷听{}消耗5个金币，账号余额：{},收益为平台",userId,condition.getQuestionId(),
                    userWallet.getDeposit()-PAY_GOLD_NUMBER);

            getBillDetail(userId,obj.getQuestionUserId(),diamond,2);

            //TODO  更新用户值
            QuestionAndAnswerPayInfo payInfo = getQuestionAndAnswerPayInfo(condition.getQuestionId(),2,
                    userId,-1L);

            //入库
            questionAndAnswerPayInfoDao.createInfo(payInfo);

        }else{
            //收益人为用户
            UserWallet entity = new UserWallet();

            entity.setUserId(userId);

            entity.setDeposit(PAY_GOLD_NUMBER);

            // 减提问者金币
            userWalletDao.minusDeposit(entity);

            log.info("用户：{}偷听{}消耗5个金币，账号余额：{}",userId,condition.getQuestionId(),
                    userWallet.getDeposit()-PAY_GOLD_NUMBER);

            // 收款者，修改剩余钻石
            UserWallet inUserWallet = userWalletDao.getUserWalletById(obj.getQuestionUserId());

            inUserWallet.setDiamond(diamond);

            userWalletDao.reviseDiamond(inUserWallet);

            log.info("用户：{}偷听问题{}消耗5个金币,提问用户{},赚取砖石{}",userId,condition.getQuestionId(),
                    obj.getQuestionUserId(),diamond);

            getBillDetail(userId,obj.getQuestionUserId(),diamond,1);

            //TODO 更新用户值
            QuestionAndAnswerPayInfo payInfo = getQuestionAndAnswerPayInfo(condition.getQuestionId(),1,
                    userId,obj.getQuestionUserId());

            //入库
            questionAndAnswerPayInfoDao.createInfo(payInfo);

        }

        //更新缓存
        questionAndAnswerPayInfoRedisDao.updateQuestionAndAnswerPayInfo(condition.getQuestionId(),userId);

    }

    /**
     * 设置账单 ,
     * @param outUserId
     * @param inUserId
     * @param diamond
     * @param type 收益人 1：个人，2：平台
     */
    private void getBillDetail(long outUserId, long inUserId ,double diamond, int type) {
        // 保存消费记录
        BillDetail billDetail = new BillDetail();
        // 消费类型13 偷听语句
        billDetail.setRecordType(RecordTypeEnum.EAVESDROPPING_STATEMENT.state);
        //1：非主播页面偷听，2：主播页面偷听

        //如果type 为1 收益为用户
        if(type==1){
            // 赚取钻石用户id
            billDetail.setInUserId(inUserId);
        }

        // 消费金币用户id
        billDetail.setOutUserId(outUserId);
        // 赚取钻石数
        billDetail.setDiamond(diamond);
        // 消费金币数
        billDetail.setSpend(PAY_GOLD_NUMBER);

        billDetailDao.insertBillDetail(billDetail);
        log.info("生成账单："+ JSONObject.toJSONString(billDetail));
    }

    private QuestionAndAnswerPayInfo getQuestionAndAnswerPayInfo(long questionId,int type, long userId,long beneficiaryId) {

        QuestionAndAnswerPayInfo payInfo = new QuestionAndAnswerPayInfo();

        payInfo.setQuestionId(questionId);

        payInfo.setPurchaser(userId);

        payInfo.setPrice(PAY_GOLD_NUMBER);

        payInfo.setBenefitType(type);

        payInfo.setBeneficiaryId(beneficiaryId);

        payInfo.setCreateTime(LocalDateTime.now());

        payInfo.setCreateDate(LocalDate.now());

        return payInfo;
    }
}
